package dal;

import java.sql.Connection;
import java.sql.SQLException;

import javax.naming.InitialContext;
import javax.sql.DataSource;

public class ConnectionProvider {

	// TODO connection pool
	// http://tomcat.apache.org/tomcat-7.0-doc/jndi-datasource-examples-howto.html

	private static DataSource source = null;

	public static Connection genConnection() throws Exception {
		if (source == null) {
			InitialContext initContext = new InitialContext();
			source = (DataSource) initContext
					.lookup("java:/comp/env/jdbc/postgres");

			// if(source != null)
			// System.out.print("Successfully loaded!");
		}

		Connection dbConn = source.getConnection();
		// System.out.println(dbConn.toString());
		return dbConn;
	}

	public static Connection startUpdateTransaction() throws SQLException {
		Connection dbConn = source.getConnection();
		dbConn.setAutoCommit(false);
		return dbConn;
	}

	public static Connection startSelectTransaction() throws SQLException {
		Connection dbConn = source.getConnection();
		dbConn.setAutoCommit(false);
		return dbConn;
	}

	public static boolean commitTransaction(Connection dbConn)
			throws SQLException {
		boolean res = false;
		try {
			dbConn.commit();
			res = true;
		} catch (Exception e) {
			dbConn.rollback();
			res = false;
		} finally {
			dbConn.setAutoCommit(true);
		}
		return res;
	}

	public static void releaseTransaction(Connection dbConn)
			throws SQLException {
		dbConn.setAutoCommit(true);
		dbConn.close();
	}

	public static void releaseConnection(Connection dbConn) throws SQLException {
		dbConn.close();
	}

}
